package cn.basic.aspect;

import cn.basic.bean.bo.CommonBo;
import cn.basic.enums.ReturnCodeEnum;
import cn.basic.exception.DONotAlarmException;
import cn.basic.util.RespUtil;
import cn.basic.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: ZZZ
 * @time: 2021/2/24 17:45
 */
@Aspect
@Order(1)
@Component
public class RecordAspect {

    @Pointcut("execution(public * cn.basic.controller.*Controller.*(..))")
    public void executionMethod() {
    }

    @Around(value = "executionMethod()")
    public Object logAspect(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("进入日志切面类");
        Object[] params = pjp.getArgs();
        String callSn = "";
        String secretKey = "";
        if (params != null && params.length > 0) {
            String requestParam = JSONObject.toJSONString(params[0]);
            JSONObject json = JSONObject.parseObject(requestParam);
            if (json != null && json.containsKey("callSn") && json.getString("callSn") != null) {
                callSn = json.getString("callSn");
            }
            if (json != null && json.containsKey("secretKey") && json.getString("secretKey") != null) {
                secretKey = json.getString("secretKey");
            }
        }
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Exception e) {
            CommonBo commonBo=null;
            System.out.println("日志结束:exception " + e.getMessage());
            if (e instanceof DONotAlarmException) {
                ReturnCodeEnum returnCodeEnumByCode = ReturnCodeEnum.getReturnCodeEnumByCode(((DONotAlarmException) e).getCode());
                String code = returnCodeEnumByCode.getCode();
                String message = e.getMessage();
                if (StringUtils.isBlank(message)) {
                    message = returnCodeEnumByCode.getMessage();
                }
                result= RespUtil.commonResp(code, message, callSn, secretKey, result);
                return result;
            }
            result = RespUtil.commonResp(ReturnCodeEnum.REQUEST_FAIL.getCode(), ReturnCodeEnum.REQUEST_FAIL.getMessage(), callSn, secretKey, result);
        }
        System.out.println("日志结束:" + JSONObject.toJSONString(result));
        return result;

    }


}
